<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="container" id="con">

    </div>

    <!-- 定义模板结构 -->
    <script type="text.html" id="user">
        <div>
            <h1>{{name}}</h1>
            <p>{{age}}</p>
            <p>{{gender}}</p>
            <p>{{address}}</p>
        </div>
    </script>
    <script>
        //定义数据
        let data = {
            name: '张三',
            age: 18,
            gender: '男',
            address: '南京'
        };
        //调用模板引擎
        let str = template('user', data);
        //渲染html结构
        document.getElementById('con').innerHTML = str;

        //封装自己的模板引擎
        function template(id, data) {
            //获取模板
            let template = document.getElementById(id).innerHTML;
            //定义正则
            let pattern = /{{\s*([a-zA-Z]+)\s*}}/;
            //定义正则结果
            let patternResult = null;
            //循环替换
            while (patternResult = pattern.exec(template)) {
                //替换模板
                template = template.replace(patternResult[0], data[patternResult[1]]);
            }
            return template;
        }
    </script>
</body>

</html>